package farmaciaweb.com.br.dao.impl;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import farmaciaweb.com.br.dao.IndicacaoDAO;
import farmaciaweb.com.br.entity.Indicacao;
import farmaciaweb.com.br.util.JPAUtil;

@PersistenceContext(unitName = "FarmaciaWebJPA")
public class IndicacaoDAOImpl implements IndicacaoDAO{

	private static final long serialVersionUID = -2887446391348674418L;
	
	private EntityManager em;
	
	@Override
	public Indicacao saveAtomic(Indicacao indicacao) {
		Indicacao indicacaoSalva = null;
		
		try{
			this.em = JPAUtil.getEntityManger();
			this.em.getTransaction().begin();
			indicacaoSalva = this.em.merge(indicacao);
			this.em.getTransaction().commit();
			this.em.close();
		}
		catch(Exception e){
			return null;
		}	
		
		return indicacaoSalva;	
	}
	
	@Override
	public void deleteAtomic(Indicacao indic) {
		
		try{
			this.em = JPAUtil.getEntityManger();
			this.em.getTransaction().begin();
			this.em.remove(indic);
			this.em.getTransaction().commit();
			this.em.close();
		}
		catch(Exception e){
			e.getStackTrace();
		}	
		
	}
	
	public List<Indicacao> pesquisarIndicacao(String desc){
		Map<String, Object> listaParams;
		listaParams = new HashMap<String, Object>();
		listaParams.put("desc", desc);		
		return JPAUtil.findByNamedQueryAndNamedParams("bd_farmaciaweb.consultaIndicacao", listaParams);
	}
	
	public Indicacao findById(int id){
		Indicacao t = new Indicacao();
		t = em.find(Indicacao.class, id);
		return t;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Indicacao> findAll() {
		this.em = JPAUtil.getEntityManger();
		Query query = this.em.createQuery("SELECT e FROM Indicacao e ORDER BY e.descricao");
		return query.getResultList();
	}
	
	public EntityManager getEm() {
		return em;
	}

	public void setEm(EntityManager em) {
		this.em = em;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}


}
